package servlet;

import dao.Userdao;
import service.Userservice;
import vo.ResultInfo;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("username");
        String pwd = request.getParameter("password");
        Userservice userservice = new Userservice();
        ResultInfo<User> resultInfo = null;
        try {
            resultInfo = userservice.register(name, pwd);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (resultInfo.getCode() == 0) {
            request.setAttribute("error_which", resultInfo.getWhich());
            request.getRequestDispatcher("register.jsp").forward(request, response);
        } else {
            User user= resultInfo.getResult();
            Userdao userdao=new Userdao();
            try {
                userdao.setUser(user);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
